import java.io.File;
import java.io.IOException;

import javax.swing.JComponent;
import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;


public class XYChart {

	public XYChart(){

	}

	public File Plot(DetectorResults dr,String app) {
		
		

		XYSeries numNewScripts = new XYSeries("Number of New Scripts",false);
		XYSeries incrementalNewScripts = new XYSeries("Incremental Number of New Scripts (unsorted)",false);
		XYSeries incrementalNewScriptsSorted = new XYSeries("Incremental Number of New Scripts (sorted)",false);
		
		int counter=0;
		for (int n : dr.getNewScripts()){
			numNewScripts.add(counter,n);
			counter+=1;
		}
		
		counter=0;
		for (int n : dr.getNewScriptsIncremental()){
			incrementalNewScripts.add(counter,n);
			counter+=1;
		}
		
		counter=0;
		for (int n : dr.getNewScriptIncrementalSorted()){
			incrementalNewScriptsSorted.add(counter,n);
			counter+=1;
		}
		
		//         Add the series to your data set
		XYSeriesCollection dataset = new XYSeriesCollection();
		dataset.addSeries(numNewScripts);
		dataset.addSeries(incrementalNewScripts);
		dataset.addSeries(incrementalNewScriptsSorted);
		
		//         Generate the graph
		JFreeChart chart = ChartFactory.createXYLineChart(app, // Title
				"# of pages", // x-axis Label
				"# of JavaScripts", // y-axis Label
				dataset, // Dataset
				PlotOrientation.VERTICAL, // Plot Orientation
				true, // Show Legend
				true, // Use tooltips
				false // Configure chart to generate URLs?
		);
		ChartPanel cp = new ChartPanel(chart,true,true,true,true,true);
		
		//Create and set up the window.
        JFrame frame = new JFrame(app);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = cp;
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        				
		try {
			File file = new File("C:"+app.replaceAll("\\.","_")+"_chart.jpg");
			ChartUtilities.saveChartAsJPEG(file, chart, 500, 300);
			return (file);
		} catch (IOException e) {
			System.err.println("Problem occurred creating chart.");
			return (null);
		}
	}
}
